package com.campus.campusdelivery.service.impl;

import com.campus.campusdelivery.dto.OrderDto;
import com.campus.campusdelivery.dto.StatsDto;
import com.campus.campusdelivery.service.AdminService;
import com.campus.campusdelivery.repository.UserRepository;
import com.campus.campusdelivery.repository.MerchantRepository;
import com.campus.campusdelivery.repository.OrderRepository;
import com.campus.campusdelivery.constant.OrderStatus;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {
    
    private final UserRepository userRepository;
    private final MerchantRepository merchantRepository;
    private final OrderRepository orderRepository;
    
    @Override
    public StatsDto getSystemStats() {
        StatsDto stats = new StatsDto();
        
        // 统计总用户数
        stats.setTotalUsers((int) userRepository.count());
        
        // 统计商家数量
        stats.setTotalMerchants((int) merchantRepository.count());
        
        // 统计总订单数
        long totalOrders = orderRepository.count();
        stats.setTotalOrders((int) totalOrders);
        stats.setOrderCount((int) totalOrders);
        
        // 统计待处理订单
        stats.setPendingOrders((int) orderRepository.countByStatus(OrderStatus.PENDING));
        
        // 统计已完成订单
        stats.setCompletedOrders((int) orderRepository.countByStatus(OrderStatus.COMPLETED));
        
        // 统计已取消订单
        stats.setCancelledOrders((int) orderRepository.countByStatus(OrderStatus.CANCELLED));
        
        // 计算总收入（已完成订单的总金额）
        BigDecimal totalRevenue = orderRepository.getTotalRevenueByStatus(OrderStatus.COMPLETED);
        stats.setTotalRevenue(totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
        stats.setTotalSales(totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
        
        return stats;
    }
    
    @Override
    public StatsDto getTodayStats() {
        StatsDto stats = new StatsDto();
        
        // 今日开始和结束时间
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        LocalDateTime todayEnd = LocalDate.now().atTime(LocalTime.MAX);
        
        // 统计今日订单数
        int todayOrders = (int) orderRepository.countByCreateTimeBetween(todayStart, todayEnd);
        stats.setOrderCount(todayOrders);
        stats.setTotalOrders(todayOrders);
        
        // 统计今日待处理订单
        stats.setPendingOrders((int) orderRepository.countByStatusAndCreateTimeBetween(
            OrderStatus.PENDING, todayStart, todayEnd));
        
        // 统计今日已完成订单
        stats.setCompletedOrders((int) orderRepository.countByStatusAndCreateTimeBetween(
            OrderStatus.COMPLETED, todayStart, todayEnd));
        
        // 统计今日已取消订单
        stats.setCancelledOrders((int) orderRepository.countByStatusAndCreateTimeBetween(
            OrderStatus.CANCELLED, todayStart, todayEnd));
        
        // 计算今日收入
        BigDecimal todayRevenue = orderRepository.getTotalRevenueByStatusAndCreateTimeBetween(
            OrderStatus.COMPLETED, todayStart, todayEnd);
        stats.setTotalRevenue(todayRevenue != null ? todayRevenue : BigDecimal.ZERO);
        stats.setTotalSales(todayRevenue != null ? todayRevenue : BigDecimal.ZERO);
        
        // 系统总体统计（用于前端显示）
        stats.setTotalUsers((int) userRepository.count());
        stats.setTotalMerchants((int) merchantRepository.count());
        
        return stats;
    }
    
    @Override
    public List<OrderDto> getRecentOrders(int limit) {
        List<com.campus.campusdelivery.entity.Order> recentOrders = 
            orderRepository.findRecentOrders(limit > 0 ? limit : 10);
        
        return recentOrders.stream()
            .map(this::convertToOrderDto)
            .collect(Collectors.toList());
    }
    
    private OrderDto convertToOrderDto(com.campus.campusdelivery.entity.Order order) {
        OrderDto dto = new OrderDto();
        dto.setId(order.getId());
        dto.setOrderNumber(order.getOrderNumber());
        dto.setUserId(order.getUser().getId());
        dto.setUserName(order.getUser().getRealName());
        dto.setMerchantId(order.getMerchant().getId());
        dto.setMerchantName(order.getMerchant().getShopName());
        
        if (order.getDeliveryPerson() != null) {
            dto.setDeliveryPersonId(order.getDeliveryPerson().getId());
            dto.setDeliveryPersonName(order.getDeliveryPerson().getUser().getRealName());
        }
        
        dto.setStatus(order.getStatus());
        dto.setTotalAmount(order.getTotalAmount());
        dto.setDeliveryAddress(order.getDeliveryAddress());
        dto.setContactPhone(order.getDeliveryPhone());
        dto.setRemark(order.getRemark());
        dto.setOrderTime(order.getCreateTime());
        dto.setConfirmTime(order.getConfirmTime());
        dto.setCompleteTime(order.getCompletedTime());
        dto.setCancelTime(order.getCancelledTime());
        dto.setCancelReason(order.getCancelReason());
        
        return dto;
    }
}
